<?php


/**
 * This is the model class for table "zy_status".
 *
 * The followings are the available columns in table 'zy_status':
 * @property integer $status_id
 * @property integer $customer_id
 * @property integer $campaign_id
 * @property integer $agent_id
 * @property string $status
 * @property string $callback_date_and_time
 * @property string $last_called_date_and_time
 * @property string $notes
 * @property string $follow_up
 * @property string $sign_up_date
 * @property string $contract_expire_date
 * @property string $package
 */
class Status extends CActiveRecord {
	/**
	 * Returns the static model of the specified AR class.
	 * @param string $className active record class name.
	 * @return Status the static model class
	 */
	public static function model($className = __CLASS__) {
		return parent :: model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName() {
		return 'zy_potential_status';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules() {
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array (
			array (
				'customer_id,campaign_id, agent_id',
				'numerical',
				'integerOnly' => true
			),
			array (
				'status, callback_date_and_time, last_called_date_and_time, notes, follow_up, sign_up_date, contract_expire_date, package,followup_statusid',
				'length',
				'max' => 255
			),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array (
				'status_id, customer_id,campaign_id, agent_id, status, callback_date_and_time, last_called_date_and_time, notes, follow_up, sign_up_date, contract_expire_date, package，followup_statusid',
				'safe',
				'on' => 'search'
			),
			
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations() {
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array ();
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels() {
		return array (
			'status_id' => Yii :: t('base', 'CallStatusID'),
			'customer_id' => Yii :: t('base', 'Customer'),
			'campaign_id' => Yii :: t('base', 'Campaign'),
			'agent_id' => Yii :: t('base', 'Telesales People'),
			'status' => Yii :: t('base', 'CallStatus'),
			'callback_date_and_time' => Yii :: t('base', 'Callback Date And Time'),
			'last_called_date_and_time' => Yii :: t('base', 'Last Called Date And Time'),
			'notes' => Yii :: t('base', 'Note') . ':',
			'follow_up' => Yii :: t('base', 'follow up'),
			'sign_up_date' => Yii :: t('base', 'sign up date'),
			'contract_expire_date' => Yii :: t('base', 'Contract Expire date'),
			'package' => Yii :: t('base', 'Package'),
			'followup_statusid' => Yii :: t('base', 'Followup Statusid'),
			
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search($last_called_date_and_time) {
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria = new CDbCriteria;
		$criteria->compare('campaign_id', $this->campaign_id);
		$criteria->compare('status_id', $this->status_id);
		$criteria->compare('customer_id', $this->customer_id);
		if ($this->agent_id > 0)
			$criteria->compare('agent_id', $this->agent_id);
		if ($this->status > 0)
			$criteria->compare('status', $this->status, true);
		$criteria->compare('callback_date_and_time', $this->callback_date_and_time, true);
		if ($this->last_called_date_and_time == date("Y-m-d")) {
			$criteria->compare('last_called_date_and_time', $this->last_called_date_and_time, true);
		} else {
			//高级搜索按日期范围查询
			$criteria->addBetweenCondition('last_called_date_and_time', $this->last_called_date_and_time . " 00:00:00", $last_called_date_and_time . " 23:59:59");
		}
		/*$criteria->addSearchCondition('last_called_date_and_time',date("Y-m-d"));*/
		$criteria->compare('notes', $this->notes, true);
		$criteria->compare('follow_up', $this->follow_up, true);
		$criteria->compare('sign_up_date', $this->sign_up_date, true);
		$criteria->compare('contract_expire_date', $this->contract_expire_date, true);
		$criteria->compare('package', $this->package, true);
		$criteria->compare('followup_statusid', $this->followup_statusid, true);
		return new CActiveDataProvider($this, array (
			'criteria' => $criteria,
			'sort' => array (
				//'defaultOrder'=>'status desc',
				'defaultOrder' => 'follow_up desc',
				
			),
			
		));
	}
	//详细通话记录
	public function searchdetail() {
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria = new CDbCriteria;
		$criteria->compare('campaign_id', $this->campaign_id);
		$criteria->compare('status_id', $this->status_id);
		$criteria->compare('customer_id', $this->customer_id);
		$criteria->compare('agent_id', $this->agent_id);
		$criteria->compare('status', $this->status, true);
		$criteria->compare('callback_date_and_time', $this->callback_date_and_time, true);
		$criteria->compare('last_called_date_and_time', $this->last_called_date_and_time, true);
		/*$criteria->addSearchCondition('last_called_date_and_time',date("Y-m-d"));*/
		$criteria->compare('notes', $this->notes, true);
		$criteria->compare('follow_up', $this->follow_up, true);
		$criteria->compare('sign_up_date', $this->sign_up_date, true);
		$criteria->compare('contract_expire_date', $this->contract_expire_date, true);
		$criteria->compare('package', $this->package, true);
		$criteria->compare('followup_statusid', $this->followup_statusid, true);
		return new CActiveDataProvider($this, array (
			'criteria' => $criteria,
			'sort' => array (
				//'defaultOrder'=>'status desc',
				'defaultOrder' => 'follow_up desc',
				
			),
			
		));
	}
	//通过状态id得到状态的名字
	public function getStatusName($statusid) {
		if ($statusid == 1) {
			$statusname = "No Answer";
		}
		elseif ($statusid == 2) {
			$statusname = "Busy or Not Available";
		}
		elseif ($statusid == 3) {
			$statusname = "Invalid Number";
		}
		elseif ($statusid == 4) {
			$statusname = "Do not call again";
		}
		elseif ($statusid == 5) {
			$statusname = "No interest";
		}
		elseif ($statusid == 6) {
			$statusname = "Qualified lead";
		}
		elseif ($statusid == 7) {
			$statusname = "Won";
		}
		return $statusname;
	}

	//发送邮件给客户
	function sendEmail($email_to, $templet, $attachments) {
		spl_autoload_unregister(array('YiiBase','autoload'));  //注销YII的自动加载，采用手动导入
		include_once(dirname(dirname(__FILE__)).'/extensions/PHPMailer/class.phpmailer.php'); //按照自己的路径导入类文件
		spl_autoload_register(array('YiiBase','autoload')); //重新启用YII的自动载入
		
		$email_message = file_get_contents ( "http://cp.netcube.com.au/newsletter.html" );
		if($templet==1){
			$email_message = str_replace ( "{first_name}", "ADSL+宽带", $email_message );
		}elseif($templet==2){
			$email_message = str_replace ( "{first_name}", "产品套餐", $email_message );
		}
		$mail = new PHPMailer(); //实例化
		$mail->CharSet  = "UTF-8"; //字符集
		$mail->Encoding = "base64"; //编码方式
		$mail->Username = "sales@netcube.com.au";  //你的邮箱
		//$mail->Password = "xxx";  //你的密码
		$mail->Subject = "Netcube - 对套餐感不感兴趣"; //邮件标题
		$mail->From = "sales@netcube.com.au";  //发件人地址（也就是你的邮箱）
		$mail->FromName = "Netcube";  //发件人姓名
		$address = $email_to;//收件人email
		$mail->AddAddress($address, $email_to);//添加收件人（地址，昵称）
		//上传附件的内容
		$attach=explode('|',$attachments);
		for($i=0;$i<count($attach);$i++){
			if($attach[$i]==0){
				$address1=dirname(dirname(dirname(__FILE__))).'/newsletter.html';
				$mail->AddAttachment($address1,'newsletter.html'); // 添加附件,并指定名称
			}elseif($attach[$i]==1){
				$address2=dirname(dirname(dirname(__FILE__))).'/newsletteren.html';
				$mail->AddAttachment($address2,'newsletteren.html'); // 添加附件,并指定名称
			}
		}
		$mail->IsHTML(true); //支持html格式内容
		$mail->Body = $email_message; //邮件主体内容
		//发送
		if(!$mail->Send()) {
			return 0; //失败
		} else {
			return 1; //成功
		}
}
	/**
	
	 * report 汇总报告
	
	 * @return number
	
	 */

	public function getReport($agent_id, $starTtime, $endTime) {
		$sql = "select * from zy_user where level=12 ";
		$sql_where = "and user_id=" . $agent_id;
		if (!empty ($agent_id)) {
			$sql = $sql . $sql_where;
		}
		$result = Yii :: app()->db->createCommand($sql)->queryAll();

		for ($j = 0; $j < count($result); $j++) {

			$status = array ();

			$status_result = array ();

			$sqlstatus = "SELECT STATUS as status,COUNT(STATUS) as num FROM `zy_potential_status` WHERE agent_id=" . $result[$j]['user_id'];
			$sqlstatus_where = " AND last_called_date_and_time BETWEEN '" . $starTtime . "' and '" . $endTime . "'";
			$sqlstatusWhere = " GROUP BY STATUS ASC";
			if (!empty ($starTtime) && !empty ($endTime)) {
				$sqlstatus = $sqlstatus . $sqlstatus_where . $sqlstatusWhere;
			} else {
				$sqlstatus = $sqlstatus . $sqlstatusWhere;
			}
			//echo $sqlstatus;die();
			$resultstatus = Yii :: app()->db->createCommand($sqlstatus)->queryAll();

			for ($i = 0; $i < count($resultstatus); $i++) {

				if ($resultstatus[$i]['status'] > 0) {

					$status[$resultstatus[$i]['status']] = $resultstatus[$i]['num'];

				}

			}

			for ($k = 1; $k < 8; $k++) {

				$status_result[$k] = $status[$k] > 0 ? $status[$k] : 0;

			}

			$sql_count = "SELECT COUNT(status_id) as total FROM zy_potential_status WHERE agent_id=" . $result[$j]['user_id'] . " AND STATUS>0";
			if (!empty ($starTtime) && !empty ($endTime)) {

				$sql_count = $sql_count . $sqlstatus_where;

			}
			$count_result = Yii :: app()->db->createCommand($sql_count)->queryAll();

			$rs[$j]['mingxi'] = $status_result;

			$rs[$j]['agent_id'] = $result[$j]['user_id'];

			$rs[$j]['agent_name'] = $result[$j]['user_name'];

			$rs[$j]['total'] = $count_result[0]['total'];

			if ($count_result[0]['total'] > 0) {

				$rs[$j]['rate'] = round($status_result[6] / $count_result[0]['total'] * 100, 2);
				$match = "/^\-?[1-9]{1}[0-9]*$|^[0]{1}$/";
				if (preg_match($match, $rs[$j]['rate'])) {
					$rs[$j]['rate'] = $rs[$j]['rate'] . ".00%";
				} else {
					$rs[$j]['rate'] = $rs[$j]['rate'] . "%";
				}
			} else {

				$rs[$j]['rate'] = "0.00%";

			}

		}

		return $rs;

	}
	//判断跟进时间
	public function getfollowupstatus($followup_statusid, $follow_up) {
		if ($followup_statusid == 0 && $follow_up == null) {
			$this->followup_statusid = Yii :: t('base', 'No need to follow up');
		}
		elseif ($followup_statusid == 0 && $follow_up != null) {
			$this->followup_statusid = Yii :: t('base', 'Does not follow up');
		}
		elseif ($followup_statusid > 0 && $follow_up != null) {
			$this->followup_statusid = Yii :: t('base', 'To follow up');
		}
		return $this->followup_statusid;
	}
}